<template>
  <div>
    <el-row>
      <el-col :span="roleSpan">
        <el-card class="card">
          <!-- 搜索 -->
          <SearchForm
              :searchConfig="searchConfig"
              :form_data.sync="listQuery"
              @search="search"
              @reset="reset"
              v-if="searchConfig.length > 0"
          ></SearchForm>

          <!-- 列表 -->
          <Table
            v-loading="loading"
            ref="Table"
            :data="tableData"
            :config="tableConfig"
            :handlerBtnConfig="handlerBtnConfig"
          >
            <template slot="operation" slot-scope="scope">
              <el-button type="primary" size="mini" @click="handleEdit(scope.row.id)">编辑</el-button>
              <el-button type="warning" size="mini" @click="handleUserAssignment(scope.row)">用户</el-button>
              <el-button type="warning" size="mini" @click="handlePermsAssignment(scope.row)">权限</el-button>
              <el-button type="danger" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
            </template>
          </Table>
          <Pagination :currentPage="listQuery.pageNum" :pageSize="listQuery.pageSize" :total="total" @handleChange="handleChange"/>
        </el-card>
      </el-col>

      <transition name="el-zoom-in-top">
        <div v-show="transitionShow" class="transition-box">
          <!-- 用户信息 -->
          <el-col :span="24 - roleSpan" class="assign-show" v-if="transitionShowType === 'user'">
            <el-card class="card">
              <div slot="header" class="clearfix">
                <el-tag size="small" effect="dark">{{ this.roleName }}</el-tag>
                <el-tooltip class="item" content="分配" effect="light" placement="bottom-start">
                  <el-button type="success" size="mini" icon="el-icon-check" class="assign-button" circle @click="handleAssignUser()"/>
                </el-tooltip>
                <el-tooltip class="item" content="关闭" effect="light" placement="bottom-start">
                  <el-button type="info" size="mini" icon="el-icon-close" class="assign-button" circle @click="handleSpanChange()"/>
                </el-tooltip>
              </div>
              <!-- 用户展示 start -->
              <div style="text-align: center">
                <el-transfer
                style="text-align: left; display: inline-block"
                v-model="assignmentUserList"
                filterable
                :titles="['可分配用户', '已分配用户']"
                :format="{
                    noChecked: '${total}',
                    hasChecked: '${checked}/${total}'
                }"
                :data="unAssignmentUserList"/>
              </div>
              <!-- 用户展示 end -->
            </el-card>
          </el-col>

          <!-- 权限信息 -->
          <el-col :span="24 - roleSpan" class="assign-show" v-if="transitionShowType === 'perms'">
            <el-card class="card">
              <div slot="header" class="clearfix">
                <el-tag size="small" effect="dark">{{ this.roleName }}</el-tag>
                <el-tooltip class="item" content="授权" effect="light" placement="bottom-start">
                  <el-button type="success" size="mini" icon="el-icon-check" class="assign-button" circle @click="handleAssignPerms()"/>
                </el-tooltip>
                <el-tooltip class="item" content="关闭" effect="light" placement="bottom-start">
                  <el-button type="info" size="mini" icon="el-icon-close" class="assign-button" circle @click="handleSpanChange()"/>
                </el-tooltip>
              </div>
              <!-- 权限展示 start -->
              <el-tree
                :data="treeData"
                ref="treeRef"
                show-checkbox
                node-key="id"
                :default-checked-keys="checkedKeys"
                :default-expand-all= true
                :props="treeProps">
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                      <span>
                        <i v-if="data.icon" :class="data.icon"/>
                        <i v-else class="el-icon-folder"/>
                        {{ node.label }}
                      </span>
                  </span>
              </el-tree>
              <!-- 权限展示 end -->
            </el-card>
          </el-col>
        </div>
      </transition>
    </el-row>

    <!-- 编辑与添加 -->
    <role-form ref="addForm" @saveAfter="saveAfter"/>

  </div>
</template>

<script>

import SearchForm from '@/common/SearchForm'
import Table from '@/common/Table'
import Pagination from '@/common/Pagination'
import RoleForm from './roleForm'
import { tableConfig, searchConfig } from './roleConfig'
import { getRoleList, deleteByLogic } from '@/api/sys/role'
import { getUnAssignmentUserList } from '@/api/sys/user'
import { getUserIdListByRoleId, assignmentUser } from '@/api/sys/roleUser'
import { findMenuTree } from '@/api/sys/menu'
import { getMenuIdListByRoleId, assignmentMenu } from '@/api/sys/roleMenu'

export default {
  components: {
    SearchForm,
    Table,
    Pagination,
    RoleForm
  },
  data() {
    return {
      loading: false,
      tableData: [],
      tableConfig: tableConfig(),
      searchConfig: searchConfig(),
      roleSpan: 24,
      transitionShow: false,
      transitionShowType: '',
      handlerBtnConfig: [
        {
          label: "新增",
          type: "primary",
          size: "mini",
          round: false,
          plain: false,
          icon: "el-icon-plus",
          handler: () => {
            this.handleAdd()
          }
        }
      ],
      listQuery: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      assignmentUserList: [],
      unAssignmentUserList: [],
      treeData: [],
      checkedKeys: [],
      treeProps: {
        children: 'children',
        label: 'menuName'
      },
      roleId: '',
      roleName: ''
    }
  },
  created() {
    this.handleGetList()
  },
  methods: {
    search() {
      this.listQuery.pageNum = 1
      this.handleGetList()
    },
    reset() {
      this.listQuery = {
        pageNum: 1,
        pageSize: 10
      }
    },
    // 获取列表
    handleGetList() {
      getRoleList(this.listQuery).then(res => {
        if (res.status === 200) {
          this.tableData = res.data.list
          this.total = res.data.total
        }
      })
    },
    // 分页事件
    handleChange(pageParam) {
      this.listQuery.pageNum = pageParam.currentPage
      this.listQuery.pageSize = pageParam.pageSize
      this.handleGetList()
    },
    // 添加
    handleAdd: function() {
      this.$refs.addForm.create()
    },
    // 编辑
    handleEdit: function(id) {
      this.$refs.addForm.update(id)
    },
    saveAfter() {
      this.handleGetList()
    },
    // 删除
    handleDelete(id) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
          deleteByLogic(id).then(res => {
              if (res.status === 200) {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
                this.handleGetList()
              } else {
                this.$message({
                  type: 'info',
                  message: res.message
                })
              }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除！'
          })
        })
    },
    // 根据角色获取用户
    handleUserAssignment(row) {
      this.assignmentUserList = []
      this.roleId = row.id
      this.roleName = row.roleName
      this.roleSpan = 14
      this.transitionShow = true
      this.transitionShowType = 'user'
      getUserIdListByRoleId(row.id).then(res => {
          if (res.status === 200) {
              this.assignmentUserList = res.data
          }
      })
      getUnAssignmentUserList(row.id).then(res => {
          if (res.status === 200) {
              this.unAssignmentUserList = res.data
          }
      })
    },
    // 分配用户
    handleAssignUser() {
        const data = {
            roleId: this.roleId,
            userIdList: this.assignmentUserList
        }
        assignmentUser(data).then(res => {
            if (res.status === 200) {
              this.$notify({
                title: '成功',
                message: '分配成功！',
                type: 'success'
              });
            }
        }).catch(()=> {
            this.loading = false
        })
    },
    // 根据角色获取权限
    handlePermsAssignment(row) {
      this.roleId = row.id
      this.roleName = row.roleName
      this.roleSpan = 18
      this.transitionShow = true
      this.transitionShowType = 'perms'
      findMenuTree().then(res => {
        if (res.status === 200) {
            this.treeData = res.data
        }
      })
      getMenuIdListByRoleId(row.id).then(res => {
        if (res.status === 200) {
            this.checkedKeys = res.data
        }
      })
    },
    // 分配权限
    handleAssignPerms() {
      const keys = [
          ...this.$refs.treeRef.getCheckedKeys()
          // ,
          // ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const data = {
          roleId: this.roleId,
          menuIdList: keys
      }
      assignmentMenu(data).then(res => {
          if (res.status === 200) {
              this.$notify({
                title: '成功',
                message: '授权成功！',
                type: 'success'
              });
          }
      }).catch(()=> {
          this.loading = false
      })
    },
    handleSpanChange() {
      this.roleSpan = 24
      this.transitionShow = false
      this.type = ''
    }
  }
}
</script>

<style scoped>
.card {
  height: 100%;
  margin: 15px;
}
.assign-show {
  padding-left: 10px;
}
.assign-button {
  float: right; 
  margin-left: 10px;
}
</style>

 